# 设置CMake最低版本和项目名称
cmake_minimum_required(VERSION 3.31)
project(Demo1_1)

# 设置C++标准和Qt自动处理选项
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_AUTOMOC ON) # 启用MOC自动处理，处理信号与槽，将.h文件转换为.moc文件
set(CMAKE_AUTORCC ON) # 启用RCC自动处理，处理资源文件，将.qrc文件转换为.cpp文件
set(CMAKE_AUTOUIC ON) # 启用UIC自动处理，处理.ui文件，将其转换为.h文件

# 查找Qt6所需组件
find_package(Qt6 COMPONENTS
        Core
        Gui
        Widgets
        REQUIRED)

# 添加可执行文件及其源文件
add_executable(Demo1_1 main.cpp
        dlg.cpp
        dlg.h
        dlg.ui)

# 链接Qt库
target_link_libraries(Demo1_1
        Qt::Core
        Qt::Gui
        Qt::Widgets
)

# Windows平台下处理Qt DLL和插件的拷贝
if (WIN32 AND NOT DEFINED CMAKE_TOOLCHAIN_FILE)
    set(DEBUG_SUFFIX)
    if (MSVC AND CMAKE_BUILD_TYPE MATCHES "Debug")
        set(DEBUG_SUFFIX "d")
    endif ()
    set(QT_INSTALL_PATH "${CMAKE_PREFIX_PATH}")
    if (NOT EXISTS "${QT_INSTALL_PATH}/bin")
        set(QT_INSTALL_PATH "${QT_INSTALL_PATH}/..")
        if (NOT EXISTS "${QT_INSTALL_PATH}/bin")
            set(QT_INSTALL_PATH "${QT_INSTALL_PATH}/..")
        endif ()
    endif ()
    # 拷贝平台插件DLL
    if (EXISTS "${QT_INSTALL_PATH}/plugins/platforms/qwindows${DEBUG_SUFFIX}.dll")
        add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E make_directory
                "$<TARGET_FILE_DIR:${PROJECT_NAME}>/plugins/platforms/")
        add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E copy
                "${QT_INSTALL_PATH}/plugins/platforms/qwindows${DEBUG_SUFFIX}.dll"
                "$<TARGET_FILE_DIR:${PROJECT_NAME}>/plugins/platforms/")
    endif ()
    # 拷贝Qt库DLL
    foreach (QT_LIB Core Gui Widgets)
        add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E copy
                "${QT_INSTALL_PATH}/bin/Qt6${QT_LIB}${DEBUG_SUFFIX}.dll"
                "$<TARGET_FILE_DIR:${PROJECT_NAME}>")
    endforeach (QT_LIB)
endif ()
